package com.lwq.logtrace.core.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lwq.logtrace.common.Constants;
import com.lwq.logtrace.tookit.LogTraceContextHolder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * @author 刘文强
 *
 * 日志链路过滤器,从请求头中获取日志链路信息
 */
public class LogTraceFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try{
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //先从header中取traceId,如果取不到，在生成
            String traceId = request.getHeader(Constants.LOG_TRACE_ID_HEADER);
            if (StrUtil.isBlank(traceId)){
                traceId = IdUtil.simpleUUID();
            }
            LogTraceContextHolder.set(traceId);
            filterChain.doFilter(servletRequest, servletResponse);
        }finally {
            LogTraceContextHolder.remove();
        }
    }

    @Override
    public void destroy() {

    }
}
